// Copyright (c) 2000 Just Objects B.V. <just@justobjects.nl>
// Distributable under LGPL license. See terms of license at gnu.org.

package nl.justobjects.pushlet.servlet;

import nl.justobjects.pushlet.core.PulletSubscriber;
import nl.justobjects.pushlet.core.Log;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Servlet that creates PulletSubscriber on first request and reinvokes on next requests.
 *
 * @version $Id: Pullet.java,v 1.2 2003/08/15 08:37:40 justb Exp $
 * @author Just van den Broecke - Just Objects &copy;
 */
public class Pullet extends HttpServlet {

	/** Servlet GET request: instantiates or continues with PushletPullSubscriber. */
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String id = request.getParameter("id");
		PulletSubscriber pulletSubscriber = null;

		if (id == null || "".equals(id)) {
			// Make a new and unique id; we don't use the Session id since
			// we need to handle more requests from the same client. This way
			// we can now uniquely determine the pull subscriber instance.
			id = System.currentTimeMillis() + "";

			// First time: Create a new subscriber
			pulletSubscriber = new PulletSubscriber(id);

			try {
				// One-time initialization
				pulletSubscriber.init(request, response);
			}
			catch (IOException ioe) {
				Log.warn("Pullet: IOException in init()");
			}
		}
		else {
			// We have an id: try to get the active subscriber
			pulletSubscriber = PulletSubscriber.get(id);

			// Continue if valid.
			if (pulletSubscriber != null) {
				// Aha back again: continue returning events
				pulletSubscriber.initContinue(request, response);
			}
			else {
				// Hmm. We left in the meantime...
				// TODO: return a useful error/alert.
				Log.warn("No pullet subscriber for id=" + id);
				return;
			}
		}

		// In all cases will it need to handle events
		pulletSubscriber.processEvents();
	}
}

/*
 * $Log: Pullet.java,v $
 * Revision 1.2  2003/08/15 08:37:40  justb
 * fix/add Copyright+LGPL file headers and footers
 *
 * Revision 1.1  2003/08/13 13:26:57  justb
 * moved all servlets to servlet package
 *
 * Revision 1.2  2003/05/18 16:15:08  justb
 * support for XML encoded Events
 *
 * Revision 1.1.1.1  2002/09/24 21:02:31  justb
 * import to sourceforge
 *
 * Revision 1.1.1.1  2002/09/20 22:48:18  justb
 * import to SF
 *
 * Revision 1.1.1.1  2002/09/20 14:19:04  justb
 * first import into SF
 *
 * Revision 1.3  2002/04/15 20:42:41  just
 * reformatting and renaming GuardedQueue to BlockingQueue
 *
 * Revision 1.2  2000/08/21 20:48:29  just
 * added CVS log and id tags plus copyrights
 *
 *
 */

